package com.smart.mac.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.smart.mac.config.FlowServiceConfig;
import com.smart.mac.model.dto.FlowTaskDTO;
import com.smart.mac.service.FlowInstanceService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.EndEvent;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * FlowInstanceServiceImpl
 *
 * @Author mac
 */
@Slf4j
@Service
public class FlowInstanceServiceImpl extends FlowServiceConfig implements FlowInstanceService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void stopProcessInstance(FlowTaskDTO flowTaskDTO) {
        //任务已经审核不可终止
       /* List<HistoricTaskInstance> tenantHistoricTaskInstanceList = getTenantHistoricTaskInstanceList(flowTaskDTO.getInstanceId());
        if (CollectionUtil.isNotEmpty(tenantHistoricTaskInstanceList) && tenantHistoricTaskInstanceList.stream().anyMatch(x -> Objects.nonNull(x.getEndTime()))){
            throw new RuntimeException("流程已有任务审核完成，不可终止");
        }*/

        //获取租户流程实例
        ProcessInstance processInstance = getTenantProcessInstant(flowTaskDTO.getInstanceId());
        taskService.addComment(flowTaskDTO.getTaskId(),flowTaskDTO.getInstanceId(),"终止流程");
        //查询结束节点
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        Process mainProcess = bpmnModel.getMainProcess();
        EndEvent endEvent = mainProcess.findFlowElementsOfType(EndEvent.class).get(0);
        //查询执行的任务
        List<Execution> list = runtimeService.createExecutionQuery().parentId(flowTaskDTO.getInstanceId()).list();
        if (CollectionUtil.isNotEmpty(list)){
            List<String> executIds = list.stream().map(Execution::getId).collect(Collectors.toList());
            //删除当前执行的任务，指向结束，更新状态
            runtimeService.createChangeActivityStateBuilder().moveExecutionsToSingleActivityId(executIds,endEvent.getId()).changeState();
        }else{
            throw new RuntimeException("没有执行的任务");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateState(Integer state, String instanceId) {
        //获取租户流程实例
        getTenantProcessInstant(instanceId);
        // 激活
        if (state == 1) {
            runtimeService.activateProcessInstanceById(instanceId);
        }
        // 挂起
        if (state == 2) {
            runtimeService.suspendProcessInstanceById(instanceId);
        }
    }
}
